package com.joelaws.prototype.client.manage;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Image;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.UrlParam;
import com.gwtext.client.data.SimpleStore;
import com.gwtext.client.data.Store;
import com.gwtext.client.util.JavaScriptObjectHelper;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.ComboBox;
import com.gwtext.client.widgets.form.DateField;
import com.gwtext.client.widgets.form.FormPanel;
import com.gwtext.client.widgets.form.Radio;
import com.gwtext.client.widgets.layout.FitLayout;
import com.gwtext.client.widgets.layout.FormLayout;
import com.gwtextux.client.widgets.upload.UploadDialog;
import com.gwtextux.client.widgets.upload.UploadDialogListenerAdapter;
import com.joelaws.prototype.client.data.NetworkingDetails;
import com.joelaws.prototype.client.data.User;
import com.joelaws.prototype.client.data.NetworkingDetails.Degree;
import com.joelaws.prototype.client.data.NetworkingDetails.Employment;
import com.joelaws.prototype.client.data.NetworkingDetails.Income;
import com.joelaws.prototype.client.data.NetworkingDetails.Religion;
import com.joelaws.prototype.client.rpc.Manage;
import com.joelaws.prototype.client.rpc.ManageAsync;

public class ManageNetworkingTab extends Panel {

	final private User user;

	public ManageNetworkingTab(User user) {
		this.user = user;
		setBorder(false);
		setFrame(true);
		setTitle("Manage Networking");
		setLayout(new FitLayout());
		add(getFormPanel());
	}

	private Panel getFormPanel() {
		final FormPanel formPanel = new FormPanel();

		formPanel.setAutoScroll(true);
		formPanel.setHeight(600);
		formPanel.setTitle("Profile Details");
		formPanel.setLayout(new FormLayout());

		String picLoc;
		if (user.getPicture() == null) {
			picLoc = "images/space_ghost.png";
		} else {
			picLoc = user.getPicture().getLocation();
			System.out.println("Using pic location: " + picLoc);
		}

		final Image image = new Image(picLoc);
		image.setSize("50px", "50px");
		formPanel.add(image);

		Button button = new Button("Upload Picture", new ButtonListenerAdapter() {

			public void onClick(final Button button, EventObject e) {
				UploadDialog dialog = new UploadDialog();
				dialog.addListener(new UploadDialogListenerAdapter() {

					public void onUploadFailed(UploadDialog source, String filename) {
						System.out.println("onUploadFailed");
						System.out.println("filename=" + filename);
					}

					public void onUploadSuccess(UploadDialog source, String filename, JavaScriptObject data) {
						System.out.println("onUploadSuccess");
						System.out.println("filename=" + filename);
						System.out.println("code=" + JavaScriptObjectHelper.getAttribute(data, "code"));
						updateUser();
					}

					public boolean onBeforeAdd(UploadDialog source, String filename) {
						System.out.println("onBeforeAdd");
						System.out.println("filename=" + filename);
						return true;
					}

					public void onFileAdd(UploadDialog source, String filename) {
						System.out.println("onFileAdd");
						System.out.println("filename=" + filename);
					}

					public void onFileRemove(UploadDialog source, String filename) {
						System.out.println("onFileRemove");
						System.out.println("filename=" + filename);
					}

					public void onFileUploadStart(UploadDialog source, String filename) {
						System.out.println("onFileUploadStart");
						System.out.println("filename=" + filename);
					}

					public void onResetQueue(UploadDialog source) {
						System.out.println("onResetQueue");
					}

					public void onUploadComplete(UploadDialog source) {
						System.out.println("onUploadComplete");
						updateUser();
					}

					public void onUploadError(UploadDialog source, String filename, JavaScriptObject data) {
						System.out.println("onUploadError");
						System.out.println("filename=" + filename);
						System.out.println("code=" + JavaScriptObjectHelper.getAttribute(data, "code"));
						updateUser();
						// source.hide();
					}

					public void onUploadStart(UploadDialog source) {
						System.out.println("onUploadStart");
					}

					public void onUploadStop(UploadDialog source) {
						System.out.println("onUploadStart");
					}

					private void updateUser() {
						String url = "images/people/" + user.getUserID() + ".png";
						user.getNetworkingService().getPicture().setLocation(url);
						image.setUrl(url);
						formPanel.doLayout();
					}
				});
				dialog.setUrl("UploadPicture");
				dialog.setPermittedExtensions(new String[] { "png" });
				UrlParam param[] = new UrlParam[1];
				param[0] = new UrlParam("userID", user.getUserID());
				dialog.setBaseParams(param);
				dialog.setPostVarName("filename");
				dialog.show();
			}
		});
		formPanel.add(button);

		final DateField bday = new DateField("Birthday", "m/d/y");

		final Radio male = new Radio("Male", "sex");
		final Radio female = new Radio("Female", "sex");

		final ComboBox religion = getChoices("Religion", NetworkingDetails.Religion.values());

		final ComboBox degree = getChoices("Degree", NetworkingDetails.Degree.values());
		final ComboBox employment = getChoices("Employment", NetworkingDetails.Employment.values());

		final ComboBox income = getChoices("Income", NetworkingDetails.Income.values());

		NetworkingDetails details = user.getNetworkingDetails();

		if (details != null) {

			if (details.getBirthday() != null) {
				bday.setValue(details.getBirthday());
			}

			if (user.isMale()) {
				male.setValue(true);
			} else {
				female.setValue(true);
			}

			if (details.getReligion() != null) {
				religion.setValue(details.getReligion().toString());
			}

			if (details.getDegree() != null) {
				degree.setValue(details.getDegree().toString());
			}

			if (details.getEmployment() != null) {
				employment.setValue(details.getEmployment().toString());
			}

			if (details.getIncome() != null) {
				income.setValue(details.getIncome().toString());
			}

		}

		formPanel.add(bday);
		formPanel.add(male);
		formPanel.add(female);
		formPanel.add(income);
		formPanel.add(employment);
		formPanel.add(degree);
		formPanel.add(religion);

		formPanel.add(new Button("Save", new ButtonListenerAdapter() {

			public void onClick(Button button, EventObject event) {
				System.out.println("Saving networking details...");

				Religion r = null;
				if (religion.getValue() != null)
					r = Religion.valueOf(religion.getValue());

				Degree d = null;
				if (degree.getValue() != null)
					d = Degree.valueOf(degree.getValue());

				Employment e = null;
				if (employment.getValue() != null)
					e = Employment.valueOf(employment.getValue());

				Income i = null;
				if (income.getValue() != null)
					i = Income.valueOf(income.getValue());
				NetworkingDetails networkingDetails = new NetworkingDetails(user.getUserID(), male.getValue(), bday
						.getValue(), r, d, e, i);

				user.setNetworkingDetails(networkingDetails);

				ManageAsync manage = Manage.Util.getInstance();
				System.out.println("Making ajax networking details save...");
				manage.updateUser(user, new AsyncCallback<Object>() {

					public void onFailure(Throwable caught) {
						System.out.println("Failed to update user in ManageDatingTab due to " + caught.getMessage());

					}

					public void onSuccess(Object result) {
						System.out.println("Successfully update users dating details");
						MessageBox.alert("Saved");
					}
				});

			}
		}));
		return formPanel;
	}

	public String[][] getAsDoubleArray(Enum<?>[] array) {
		String[][] arr = new String[array.length][1];
		for (int i = 0; i < array.length; i++) {
			arr[i][0] = array[i].name();
		}
		return arr;
	}

	private ComboBox getChoices(String type, Enum<?>[] choices) {

		final Store store = new SimpleStore(new String[] { "type" }, getAsDoubleArray(choices));
		store.load();

		final ComboBox cb = new ComboBox();
		cb.setForceSelection(true);
		cb.setMinChars(1);
		cb.setFieldLabel(type);
		cb.setStore(store);
		cb.setDisplayField("type");
		cb.setMode(ComboBox.LOCAL);
		cb.setTriggerAction(ComboBox.ALL);
		cb.setEmptyText("Select " + type);
		cb.setLoadingText("Searching...");
		cb.setTypeAhead(true);
		cb.setSelectOnFocus(true);
		cb.setWidth(200);

		cb.setHideTrigger(false);
		return cb;
	}
}
